<script setup lang="ts">
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount, watch, markRaw, nextTick } from 'vue'

const chartDom = <any>ref(null)
const myChart = <any>ref(null)

const props = defineProps({
  options: {
    type: Object,
    default: () => {},
    required: true
  },
  titlePrimary: {
    type: String,
    default: () => ''
  },
  titleUnit: {
    type: String,
    default: () => ''
  }
})

const emit = defineEmits(['click'])

const resizeHandler = () => {
  myChart.value.resize()
}

const initChart = () => {
  console.log(myChart.value,'myChart.value')
  if (myChart.value) {
    // 关键步骤
    myChart.value.dispose()
    myChart.value = null
  }
  myChart.value = markRaw(echarts.init(chartDom.value!))
  myChart.value.setOption(props.options, true)

  myChart.value.on('click', (params: any) => {
    emit('click', params)
  })
}

const setoption = () => {
  myChart.value.setOption(props.options, true)
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  document.removeEventListener('resize', resizeHandler)
})

watch(
  () => [props.options],
  () => {
    nextTick(() => {
      initChart()
    })

    initChart()
  },
  {
    deep: true
  }
)

defineExpose({
  myChart,
  setoption
})
</script>

<template>
  <div class="w-full h-full" ref="chartDom"></div>
</template>

<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;
}
</style>
